import { BadRequestException, Injectable } from '@nestjs/common';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { ResultUtils } from 'src/common/utils/result.utils';
import { UploadImageDto } from './dto/upload-image.dto';
const fs = require('fs');
const path = require('path');
const dayjs = require('dayjs')
const crypto = require('crypto')

@Injectable()
export class UploadService {
    mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      } else {
        if (this.mkdirsSync(path.dirname(dirname))) {
          fs.mkdirSync(dirname);
          return true;
        }
      }
    }
    async uploadImage(file:Express.Multer.File,uploadImageDto:UploadImageDto) {
        const {type} = uploadImageDto;
        if(!file) {
            throw new BadRequestException('图片不能为空');
        }
        if(file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
            throw new BadRequestException('只支持jpg, png格式');
        }
        if(file.size>(1024*5000)) {
            throw new BadRequestException('大小不能超过5M');
        }
        const dirname = `${type}/${dayjs(Date.now()).format('YYYY/MM/DD')}`;
        const fileName = crypto.createHash('md5').update(`${Date.now()}${Math.random() * 1000}${file.originalname}`).digest('hex');
        const suffix = file.originalname.split('.')[file.originalname.split('.').length-1];
        this.mkdirsSync(join(__dirname,'../../../../',`upload/image/${dirname}`));
        const writeImage = createWriteStream(join(__dirname,'../../../../',`upload/image/${dirname}/${fileName}.${suffix}`));
        writeImage.write(file.buffer);     
        return ResultUtils.success(`upload/image/${dirname}/${fileName}.${suffix}`); 
    } 
}
